<template>
  <view class="content">
    <view class='ward' v-if="ward2"></view>
    <view class='wait' v-if="ward">
      <image src="../../static/wait.png" style='width: 93rpx;height: 107rpx;margin: 59rpx 206rpx 54rpx 208rpx;'>
      </image>
      <text style='color:#656565;margin-bottom: 27rpx'>支付中</text>
      <text style='color:#ff9000;'>请稍等</text>
    </view>
    <view style='width: 100%;height: 150rpx;background-color: #1976d2;'></view>
    <view class="content-view"
      style='height: 366rpx;margin-top: -110rpx;box-shadow: 0px 0px 3px 1px rgba(0, 0, 0, 0.08);border-radius: 15rpx'>
      <image class="bg-img" src="../../static/orderDetailsBgimg.png"></image>
      <view style='position: absolute;width: 100%;top: 0rpx;display: flex;flex-wrap: wrap;'>
        <text class='cabinet-number'>{{binIndex}}</text>
        <text style='height:66rpx;margin-left: 28rpx;
				   font-size34rpx;color:#009900;line-height: 66rpx;margin-top: 84rpx;'>号仓</text>
        <text class='cabinet-name'>{{dataDetail.chargingNetwork.name}}</text>
        <image v-if="dataDetail.cabinetState.signalIntensity"
          style="width: 30rpx; height: 30rpx; position: relative; top: 100rpx;left: 12rpx;"
          :src="signalData[dataDetail.cabinetState.signalIntensity]"></image>
        <image v-else style="width: 30rpx; height: 30rpx; position: relative; top: 100rpx;left: 12rpx;"
          src="/static/offLine.png">
        </image>
        <text class='cabinet-detail' style='width:588rpx;margin-top: 50rpx;'>设备编号:{{dataDetail.code || ''}}</text>
        <text class='cabinet-detail' style='width:588rpx;margin-top: 24rpx;'>设备地址:{{dataDetail.address || '暂无'}}</text>
      </view>
    </view>
    <view class="content-view">
      <!-- <view class="sells_title">
        充电柜专享套餐 特惠购卡
      </view> -->
      <!--   -->
      <view class="packetbuy" v-if="isSelling && !isWhite">
        <view class="sells_title" @click="goSellPacket">
          <text>充电柜专享套餐 特惠购卡</text>
          <button type="default" class="buy_btn">去购买</button>
        </view>
      </view>
      <view class="selling" v-else>
        <view class="sells_title">
          您是专享用户，无需支付，可直接发起充电。
        </view>
      </view>
    </view>

    <view class="content-view" style='margin-bottom:60px;'>
      <uni-card>
        <text class='explain'
          style='font-weight: bold;font-size: 36rpx;width:calc(100% - 80px);color:#393939;margin: 25rpx 0px 60rpx'>选择收费方式</text>
        <text v-if="!isWhite" style='float: right;color:#858585;margin-top: 24rpx;' @click="billingRules">收费标准 ></text>

        <view class="switchHead" v-if="tabShow && !isWhite && boubhtList.length==0">
          <view v-for="(item,index) in ['按时','按量']" class="boxList" :class="{'activeCss':activeIndex==index}"
            :key="index" @click="clickTab(index)">
            <text>{{item}}</text>
          </view>
        </view>
        <view v-if="!isWhite && boubhtList.length==0">
          <!-- 按时 -->
          <view v-if="activeIndex == 0">
            <view @click="opt(index, item)" v-for="(item, index) in durate" :key='index'>
              <view :style="{'margin-left':index % 2 == 0? '0rpx' : '40rpx'}"
                :class="['explain', 'expense', {optCost: costId == item.id}]">
                <text style='font-size: 42rpx;'>{{item.price}}元</text><text> / {{item.unit}}小时</text>
              </view>
            </view>
          </view>
          <view v-else>
            <view @click="opt(index, item)" v-for="(item, index) in quilty" :key='index'>
              <view :style="{'margin-left':index % 2 == 0? '0rpx' : '40rpx'}"
                :class="['explain', 'expense', {optCost: costId == item.id}]">
                <text>电费：{{item.price}}元/kW·h</text>
                <text>服务费：{{item.serviceFee}}元/kW·h</text>
              </view>
            </view>
          </view>
        </view>
        <view v-if="isWhite">
          <vlew :class="['explain', 'expense','optCost']" style='font-size: 42rpx;'>
            <text v-if="whiteDetail.fgFreeForever">永久免费</text>
            <text v-else-if="whiteDetail.fgWhiteList">免费
              <text class="surplus"
                v-if="whiteDetail.surplusDays&& Number(whiteDetail.surplusDays)>0">({{whiteDetail.surplusDays}}天到期)</text>
              <text class="surplus"
                v-else>({{countDown(whiteDetail.currentTime,whiteDetail.endTime).hour}}小时{{countDown(whiteDetail.currentTime,whiteDetail.endTime).minute}}分钟)</text>
            </text>
          </vlew>
        </view>
        <view v-else-if="boubhtList.length>0" :class="['explain', 'expense',{'activePac':isActive==index}]"
          :style="{'margin-left':index % 2 == 0? '0rpx' : '6%'}" v-for="(item,index) in boubhtList" :key="index"
          @click="changeActive(index,item)">
          {{item.packageName}}
        </view>
        <view v-if="!isWhite">
          <text class='explain' style='color:#3672a0;margin: 50rpx 0rpx;'>占仓费:
            充电完成后，{{dataDetail.chargeTmpl.occupyFreeDuation || 0}}小时内免费，超出{{dataDetail.chargeTmpl.occupyFreeDuation || 0}}小时，按{{dataDetail.chargeTmpl.occupyChargePrice || 0}}元/{{dataDetail.chargeTmpl.occupyChargeDuration || 0}}小时收费，最高收费{{dataDetail.chargeTmpl.occupyChargeUpperLimit || 0}}元。</text>
          <text class='explain'>提示:</text>
          <text class='explain' style='font-size: 26rpx;'>1.占仓费根据实际占仓情况进行收费，充电完成后请及时取出，以免产生不必要的费用；</text>
          <text class='explain'
            style='font-size: 26rpx;padding-bottom: 74rpx;'>2.充电过程中，提前充满、充电器过载引起意外中断、用户主动停止充电等情况支付金额不予退还</text>
        </view>
      </uni-card>
    </view>
    <button @click="doCharge" :loading="btnLoading" :disabled="btnLoading" class='immobilization-button'>发起充电</button>
  </view>
</template>

<script>
  import {
    getEnumerate
  } from '../../components/calculate/calculate.js';
  import {
    chargingCabinet,
    chargePackage,
    createOrder2,
    isWhiteList
  } from '@/api/equip.js';

  import payjs from '@/pages/my/pay.js';
  import {
    chargeEndMsg
  } from '@/config/interface.js';
  import {
    debounce
  } from '@/common/main.js';
  export default {
    mixins: [payjs],
    data() {
      return {
        dataDetail: {},
        binIndex: '', //几号仓
        equipid: '', //设备id
        orgId: '', //机构id
        isSelling: false, //是否显示购买套餐包入口
        templateItem: {}, //自费模板price item
        isWhite: false, //是否是白名单用户

        whiteDetail: {}, //是否白名单detail

        boubhtList: [], //我购买的套餐list
        isActive: 0, //选中

        signalData: {
          1: "/static/1.png",
          2: "/static/2.png",
          3: "/static/3.png",
          4: "/static/4.png",
          5: "/static/5.png",
        },
        tabShow: false,
        activeIndex: 0,
        durate: [], //按时
        quilty: [], //按量

        details: {
          data: {
            name: '',
            signal: 0,
            distance: '',
            address: '',
            leisure: 0,
            sum: 0,
            number: 0,
            power: '',
          }
        },
        ward: false,
        charge: [

        ],
        bottonName: '发起充电',
        optIndex: 0,
        timeScope: '08:00 - 21:59',
        whiteList: false,
        businessState: 1,
        // orderCode: '0a21057d-6ec4-11ec-ba62-0242ac110004',
        orderCode: '',
        businessMap: '',
        tradeAmount: 0,
        payAmount: '',
        cabinetId: '',
        cabinetBinId: '',
        chargeId: '',
        costTemplate: '[]',
        costTemplateElse: {
          explain: '',
          occupyFreeDuration: '',
          occupyChargeDuration: '',
          occupyChargePrice: '',
          occupyChargeUpperLimit: '',
          occupyFreeEndTime: '',
          occupyFreeStartTime: ''
        },
        controllerFun: '',
        tradeNo: '',
        time: '',
        ward2: false,
        userPayId: '',
        signalIntensity: '',
        createOrder: '',
        costId: '',
        overtime: 10,
        interval: true,
        costTemplateId: '',
        
        btnLoading: false,//按钮loading
      }
    },
    onLoad(option) {
      this.code = option.code;
      this.binIndex = option.binIndex;
      this.equipid = option.equipid;
    },
    filters: {
      cumPrice(val) {
        return val.price;
      }
    },
    onShow() {
      this.isSelling = false;
      this.getDataList();
    },

    methods: {
      getDataList() {
        this.$Toast.loading('加载中');
        chargingCabinet('/selectAllData', 'get', {
          code: this.code
        }).then(res => {
          uni.hideLoading();
          if (res.code == 200) {
            this.dataDetail = res.data;
            this.orgId = this.dataDetail.chargingNetwork.organization.id;

            this.durate = this.dataDetail.chargeTmpl.chargeTmplPriceList.filter(item => item.type == 'DURATION' ||
              item.type == '按时');
            this.quilty = this.dataDetail.chargeTmpl.chargeTmplPriceList.filter(item => item.type == 'QUANTITY' ||
              item.type == '按量');

            this.costId = this.durate.length > 0 ? this.durate[0].id : this.quilty[0].id;
            this.templateItem = this.durate.length > 0 ? this.durate[0] : this.quilty[0];
            if (this.durate.length > 0) {
              this.activeIndex = 0;
            } else if (this.durate.length == 0 && this.quilty.length > 0) {
              this.activeIndex = 1;
            }
            if (this.durate.length > 0 && this.quilty.length > 0) {
              this.tabShow = true;
            }
          }
          this.getIsWhite();

        }).catch(err => {
          console.log(err);
          uni.hideLoading();
        })
      },
      clickTab(index) {
        this.activeIndex = index;
        this.costId = index == 0 ? this.durate[0].id : this.quilty[0].id;
        this.templateItem = index == 0 ? this.durate[0] : this.quilty[0];
      },
      // 查询是否是白名单用户
      getIsWhite() {
        isWhiteList('/query/user/whiteList/detail', 'get', {
          orgID: this.orgId,
          cabinetId: this.equipid
        }).then(res => {
          this.whiteDetail = res.data;
          this.isWhite = res.data.fgWhiteList || this.whiteDetail.fgFreeForever; //true 白名单用户；false非白名单用户

          this.getBuyPacket();
        })
      },
      // 查询是否有进行中的订单，是，去结束；否 查询购买过套餐包,是 直接下单;否 查询可购买的套餐包
      // 查询购买过套餐包
      getBuyPacket() {
        chargePackage('/bought/list', 'get', {
          orgId: this.orgId
        }).then(res => {
          this.boubhtList = res.data;
          if (res.data.length == 0) { //未购买套餐包
            // 去购买
            this.isSelling = true;
          }
        }).catch(err => {})
      },

      loadOrder() {
        this.controllerFun({
          id: this.orderCode
        }).then(res => {
          if (res.data && res.data.businessState) {
            this.businessState = res.data.businessState;
            this.bottonName = this.businessMap.get(res.data.businessState);
            this.ward = false;
            this.ward2 = false;
            if (res.data.businessState == 1) {
              uni.redirectTo({
                url: '../charge/charge?orderID=' + this.orderCode + '&res=' + JSON
                  .stringify(res.data)
              })
            }
          } else {
            return;
          }
        })
      },

      errHint(err) {
        uni.showToast({
          title: err.message ? err.message : err.data.message,
          icon: 'none',
          duration: 1500
        })
      },
      doCharge() {
        this.btnLoading = true;
        if (!this.dataDetail.chargeTmpl || !this.dataDetail.chargeTmpl.chargeTmplPriceList || this.dataDetail.chargeTmpl
          .chargeTmplPriceList.length == 0) {
          this.btnLoading = false;
          this.$Toast.none('暂无收费方式，不能发起充电哦~');
          return;
        }
        wx.requestSubscribeMessage({
          tmplIds: [chargeEndMsg],
          complete: () => {
            this.doCreateOrder();
          }
        })
      },
      doCreateOrder() {
        // "DURATION" 按时；POWER 按功率；QUANTITY 按电量
        let that = this;
        that.$Toast.loading('订单创建中···');
        let type = '';
        if (that.whiteDetail.fgWhiteList || that.whiteDetail.fgFreeForever) { //白名单
          type = 'QUANTITY';
        } else {
          if (that.templateItem.type == '按时') {
            type = 'DURATION';
          } else if (that.templateItem.type == '按量') {
            type = 'QUANTITY';
          } else {
            type = that.templateItem.type;
          }
        }
        let priceTmp = (that.whiteDetail.fgWhiteList || that.whiteDetail.fgFreeForever) ? '' : that.costId;
        let param = {
          cabinetBinIndex: that.binIndex,
          cabinetId: that.equipid,
          priceTmpId: priceTmp,
          chargingType: type
        };
        createOrder2('/begin/charging', 'post', param).then(res => {
          if (res.code == 200) { //订单生成成功 
            let orderId = res.data.orderId;
            if (res.data.needPay) { //需要支付
              let wechatinfo = res.data.wxPrePayVO;
              that.wechatPay(wechatinfo).then(succ => {}).catch(err => {
                if (err.errMsg == 'requestPayment:ok') { //支付成功
                  uni.redirectTo({
                    url: '/pages/charge/charge?orderId=' + orderId
                  })
                } else if (err.errMsg == 'requestPayment:fail cancel') { //用户取消
                  that.$Toast.error('取消支付');
                } else {
                  that.$Toast.error('支付失败');
                }
              });
            } else {
              uni.redirectTo({
                url: '/pages/charge/charge?orderId=' + orderId
              })
            }
          }
        })
        .finally(final => {
          this.btnLoading = false;
        })
        .catch(err => {})
      },
      billingRules() {
        uni.navigateTo({
          url: '../billingRules/billingRules?code=' + this.code
        })
      },

      opt(index, item) {
        this.optIndex = index;
        this.tradeAmount = item.cost;
        this.payAmount = item.cost;
        this.costId = item.id;
        this.templateItem = item;
      },
      // 去购买 套餐
      goSellPacket() {
        uni.navigateTo({
          url: `/pages/my/package/sellPacket?orgId=${this.orgId}&code=${this.code}&binIndex=${this.binIndex}&equipid=${this.equipid}`
        })
      },
      // 切换套餐
      changeActive(index, item) {
        this.isActive = index;
      },
    }
  }
</script>

<style lang="scss" scoped>
  @import url('../commonStyle/commonStyle.css');
  @import "@/static/css/common.scss";
  @import "@/static/css/main.scss";

  .switchHead {
    width: 100%;
    border: 1px solid #3672a0;
    border-radius: 10rpx;
    line-height: 60rpx;
    color: #3672a0;
    margin-bottom: 30rpx;
    @include flexLayout(center, space-between);

    view {
      width: 50%;
      text-align: center;
    }

    .activeCss {
      background: #3672a0;
      color: #FFFFFF;
    }
  }

  .content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .content-view {
    margin: 0px 10px;
  }

  .cabinet-number {
    height: 105rpx;
    width: 105rpx;
    border: 4rpx solid #009900;
    border-radius: 90px;
    text-align: center;
    line-height: 105rpx;
    margin: 50rpx 0rpx 0rpx 50rpx;
    color: #009900;
  }

  .cabinet-name {
    margin-left: 110rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 254rpx;
    height: 66rpx;
    line-height: 66rpx;
    font-size: 34rpx;
    margin-top: 85rpx;
  }

  .cabinet-detail {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    font-size: 26rpx;
    margin-left: 43rpx;
    color: #858585
  }

  .explain {
    float: left;
    width: 100%;
  }

  .expense {
    width: 45%;
    height: 150rpx;
    @include flexLayout(center, center);
    flex-direction: column;
    margin: 0px 0px 28rpx 0rpx;
    border: 1px solid;
    border-radius: 15rpx;
    color: #3a3a3a;
    font-weight: normal;
    font-stretch: normal;

  }

  .flexed {
    @include flexLayout(center, center);
    flex-direction: column;

    text {
      display: inline-block;
    }
  }

  .bg-img {
    width: 100%;
    border-radius: 10px;
    height: 100%;
  }

  .ward {
    width: 100%;
    height: 100vh;
    background: #9e9e9e99;
    position: fixed;
    z-index: 9998;
    top: 0px;
    bottom: 0px;
  }

  .wait {
    display: flex;
    flex-direction: column;
    text-align: center;
    position: absolute;
    top: 400rpx;
    z-index: 9999;
    background: #fff;
    width: 507rpx;
    height: 400rpx;
  }

  .optCost {
    color: #fff;
    background: #65b0fb;

    .surplus {
      font-size: 28rpx;
      text-align: center;

      text {
        font-size: 36rpx;
      }
    }
  }

  .packetbuy {
    box-sizing: border-box;
    border-radius: 20rpx;
    background: #65b0fb;
    color: #ffffff;
    padding: 30rpx 30rpx;
    margin-top: 20rpx;

    .sells_title {
      font-weight: bold;
      @include flexLayout(center, space-between);

      .buy_btn {
        background: #7dbaf7;
        color: #fff;
        font-weight: normal;
        font-size: 24rpx;
        width: 140rpx;
        border-radius: 30rpx;
        margin: 0;
      }
    }

  }

  /deep/ button::after {
    border: none;
  }

  .selling {
    @include flexLayout(center, space-between);
    flex-wrap: wrap;
    padding: 40rpx 20rpx 0;

    .sells_title {
      margin-bottom: 30rpx;
      font-size: 28rpx;
    }
  }

  .activePac {
    background: #579fef;
    color: #FFFFFF;
    border-color: #598fca;
  }
</style>
